{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CdL1ZvDepO-X"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/jeffheaton/app_deep_learning/blob/main/assignments/assignment_yourname_class6.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "R_pemiL8pO-Y"
   },
   "source": [
    "# T81-558: Applications of Deep Neural Networks\n",
    "* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/index.html)\n",
    "* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).\n",
    "\n",
    "**Module 6 Assignment: Extract Text with LLM**\n",
    "\n",
    "**Student Name: Your Name**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lky4xopspO-Z"
   },
   "source": [
    "# Assignment Instructions\n",
    "\n",
    "A [file](https://s3.amazonaws.com/data.heatonresearch.com/data/t81-558/sentences.csv) is provided that contains 100 English sentences. Sample sentences from this file include:\n",
    "\n",
    "|id|sentence|\n",
    "|---|---|\n",
    "|1|Sarah found an old photograph in the attic.|\n",
    "|2|By the window, Jake noticed a sparkling diamond necklace.|\n",
    "|3|The antique clock was expertly fixed by Robert.|\n",
    "|4|At the beach, Maria stumbled upon a washed-up bottle.|\n",
    "|...|...|\n",
    "\n",
    "For each of these sentences you should extract the name of the person from the sentence. The results of this assignment would look like the following for the above input.\n",
    "\n",
    "|id|name|\n",
    "|---|---|\n",
    "|1|Sarah|\n",
    "|2|Jake|\n",
    "|3|Robert|\n",
    "|4|Maria|\n",
    "|...|...|\n",
    "\n",
    "Use a large language model (LLM) to extract the single word action from each of these sentences.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "U4LQZW_SpO-Z"
   },
   "source": [
    "# Google CoLab Instructions\n",
    "\n",
    "If you are using Google CoLab, it will be necessary to mount your GDrive so that you can send your notebook during the submit process. Running the following code will map your GDrive to ```/content/drive```."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "1ZnCEIEopO-Z",
    "outputId": "86ecbc79-6e7d-4bdc-d481-862e081e1dda"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    from google.colab import drive\n",
    "    drive.mount('/content/drive', force_remount=True)\n",
    "    COLAB = True\n",
    "    print(\"Note: using Google CoLab\")\n",
    "except:\n",
    "    print(\"Note: not using Google CoLab\")\n",
    "    COLAB = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vwx0hsWE3CQd"
   },
   "source": [
    "# OpenAI Setup\n",
    "\n",
    "To make use of this assignment, you will need to use the OpenAI API to access the LLM model. First we install it. For this assignment, it is best to use CoLab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "WRPrqvDn3jYh",
    "outputId": "f6593cce-4635-44c3-f10b-01085365ef4a"
   },
   "outputs": [],
   "source": [
    "!pip install openai"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-A83r4MU3kmk"
   },
   "source": [
    "You will need a key for this assignment. You can find it in the WUSTL Canvas page for Assignment 6. It is important that you do not share this key, it is a different key than your assignment submit key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "OPutwNcc3mwj"
   },
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "openai.api_key = \"[Insert Your Key]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PMLHwV0hpO-a"
   },
   "source": [
    "# Assignment Submit Function\n",
    "\n",
    "You will submit the 10 programming assignments electronically.  The following submit function can be used to do this.  My server will perform a basic check of each assignment and let you know if it sees any basic problems.\n",
    "\n",
    "**It is unlikely that should need to modify this function.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ozSyLCNtpO-a"
   },
   "outputs": [],
   "source": [
    "import base64\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import requests\n",
    "import PIL\n",
    "import PIL.Image\n",
    "import io\n",
    "\n",
    "# This function submits an assignment.  You can submit an assignment as much as you like, only the final\n",
    "# submission counts.  The paramaters are as follows:\n",
    "# data - List of pandas dataframes or images.\n",
    "# key - Your student key that was emailed to you.\n",
    "# no - The assignment class number, should be 1 through 1.\n",
    "# source_file - The full path to your Python or IPYNB file.  This must have \"_class1\" as part of its name.\n",
    "# .             The number must match your assignment number.  For example \"_class2\" for class assignment #2.\n",
    "def submit(data,key,no,source_file=None):\n",
    "    if source_file is None and '__file__' not in globals(): raise Exception('Must specify a filename when a Jupyter notebook.')\n",
    "    if source_file is None: source_file = __file__\n",
    "    suffix = '_class{}'.format(no)\n",
    "    if suffix not in source_file: raise Exception('{} must be part of the filename.'.format(suffix))\n",
    "    with open(source_file, \"rb\") as image_file:\n",
    "        encoded_python = base64.b64encode(image_file.read()).decode('ascii')\n",
    "    ext = os.path.splitext(source_file)[-1].lower()\n",
    "    if ext not in ['.ipynb','.py']: raise Exception(\"Source file is {} must be .py or .ipynb\".format(ext))\n",
    "    payload = []\n",
    "    for item in data:\n",
    "        if type(item) is PIL.Image.Image:\n",
    "            buffered = BytesIO()\n",
    "            item.save(buffered, format=\"PNG\")\n",
    "            payload.append({'PNG':base64.b64encode(buffered.getvalue()).decode('ascii')})\n",
    "        elif type(item) is pd.core.frame.DataFrame:\n",
    "            payload.append({'CSV':base64.b64encode(item.to_csv(index=False).encode('ascii')).decode(\"ascii\")})\n",
    "    r= requests.post(\"https://api.heatonresearch.com/assignment-submit\",\n",
    "        headers={'x-api-key':key}, json={ 'payload': payload,'assignment': no, 'ext':ext, 'py':encoded_python})\n",
    "    if r.status_code==200:\n",
    "        print(\"Success: {}\".format(r.text))\n",
    "    else: print(\"Failure: {}\".format(r.text))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "id": "H7kgvLHspO-a"
   },
   "source": [
    "# Assignment #6 Sample Code\n",
    "\n",
    "The following code provides a starting point for this assignment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "8ZPLGWgkpO-a",
    "outputId": "acc802c9-db60-4d19-c92e-6b2f63544f61"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from scipy.stats import zscore\n",
    "import string\n",
    "\n",
    "# This is your student key that I emailed to you at the beginnning of the semester.\n",
    "key = \"Gx5en9cEVvaZnjut6vfLm1HG4ZO4PsI32sgldAXj\"  # This is an example key and will not work.\n",
    "\n",
    "# You must also identify your source file.  (modify for your local setup)\n",
    "file='/content/drive/My Drive/Colab Notebooks/assignment_yourname_class6.ipynb'  # Google CoLab\n",
    "# file='C:\\\\Users\\\\jeffh\\\\projects\\\\t81_558_deep_learning\\\\assignments\\\\assignment_yourname_class6.ipynb'  # Windows\n",
    "# file='/Users/jheaton/projects/t81_558_deep_learning/assignments/assignment_yourname_class6.ipynb'  # Mac/Linux\n",
    "\n",
    "# Begin assignment\n",
    "\n",
    "df = pd.read_csv(\"https://s3.amazonaws.com/data.heatonresearch.com/data/t81-558/sentences.csv\")\n",
    "\n",
    "# Submit\n",
    "submit(source_file=file,data=[df_submit],key=key,no=6)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3.9 (torch)",
   "language": "python",
   "name": "pytorch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
